import 'package:bili_caricature/models/handle_state.dart';
import 'package:bili_caricature/pages/book_shelf/repository/home_api.dart';
import 'package:bili_caricature/pages/book_shelf/repository/home_repository.dart';
import 'package:bloc/bloc.dart';
import '../../../base/base_state.dart';
import '../../../models/response_model.dart';
import '../../../net/http_config.dart';
import '../../../net/ltt_https.dart';
import '../../../widgets/easy_loading.dart';
import '../../bloc/model/cartoon_model.dart';
import '../model/banner_model.dart';
import 'event.dart';
import 'state.dart';

class BlocStaggeredGridViewBloc extends Bloc<BiliBookShelfEvent, StaggeredGridViewState> {
  BlocStaggeredGridViewBloc() : super(StaggeredGridViewState()) {
    on<GetListDataEvent>(_getDataEvent);
  }

  /// 获取数据
  Future<void> _getDataEvent(event, emit) async {
    XsEasyLoading.showLoading();
    int page = state.page;
    List<BannerModel> bannerList = [];
    bool isNoMoreDataState = false;
    if (event.isRefresh) {
      page = 1;
    } else {
      page++;
    }
    if (page == 1) {
      ResponseModel? bannerResponseModel = await HomeRepository.getBannerData<List<BannerModel>>();
      bannerList = bannerResponseModel.data ?? [];
    }
    ResponseModel responseModel = await HomeRepository.getListData<CarDataModel>(page);
    XsEasyLoading.dismiss();

    /// 处理状态
    NetState netState = HandleState.handle(responseModel, state, successCode: 200);
    if (netState == NetState.dataSuccessState) {
      CarDataModel carDataModel = responseModel.data;
      isNoMoreDataState = false;
      if (page == 1) {
        state.dataList = handleData(carDataModel.feeds ?? []);
        if ((state.dataList ?? []).isEmpty) {
          state.netState = NetState.emptyDataState;
        }
      } else {
        if ((carDataModel.feeds ?? []).isNotEmpty) {
          state.dataList?.addAll(carDataModel.feeds ?? []);
          state.dataList = handleData(state.dataList ?? []);
        } else {
          isNoMoreDataState = true;
        }
      }
    }
    emit(state.clone()
      ..bannerList = bannerList
      ..netState = netState
      ..isNoMoreDataState = isNoMoreDataState
      ..page = page);
  }

  /// 处理数据
  List handleData(List list) {
    for (int i = 0; i < list.length; i++) {
      CartoonModel cartoonModel = list[i];
      if (i % 3 == 0) {
        cartoonModel.crossAxisCount = 2;
      } else {
        cartoonModel.crossAxisCount = 1;
      }
    }
    return list;
  }
}
